#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include "cam.h"

#include<sys/types.h>
#include<sys/stat.h>
#include<netinet/in.h>
#include<arpa/inet.h>

/***********************/
//摄像头引用变量
/***********************/
int i;
int fd;
int ret;
unsigned int width;
unsigned int height;
unsigned int size;
unsigned int index_cam;
unsigned int ismjpeg;
char *yuv;
char *rgb;
/***********************/


/***********************/
//服务器引用变量
/***********************/
char bufpic[1024*1024*2];//存放图片的内容
char buf[20];//装图片的大小
int rws;
int s;
/***********************/
//main主函数
/***********************/
int main()
{	
	
	//创建服务器
	//s = server_init("192.168.2.127",8888);
		s = server_init("0",8888);

	if(s < 0)
	{
		printf("server_init failed\n");
		return -1;
	}
	printf("s = %d\n", s);
	printf("wait for a client...\n");
	//等待连接 --> accept
	struct sockaddr_in c_addr;
	socklen_t c_len = sizeof(c_addr);   
	rws = accept(s, (struct sockaddr *)&c_addr, &c_len);
	if(rws < 0)
	{
		perror("accept");
		close(s);
		return -1;
	}
	printf("Connected\n");
	//发送数据	
	while(1)
	{
		//采集摄像头图片
		get_pic();
		//服务器发送图片大小和内容
		memset(bufpic, 0, 1024*1024);
		memset(buf, 0, 20);		
		int fd2 = open("carPlate.jpg", O_RDONLY);
		if(fd2 < 0)
		{
			perror("open 83");
			close(s);
			return -1;
		}
		int len = 0;//保存图片大小
		//求图片大小
		while(1)
		{
			int ret = read(fd2, bufpic+len, 1024);
			if(ret <= 0)
				break;

			len = len + ret;
		}		
		//把图片大小写入buf
		sprintf(buf, "%d", len);	
		//发送图片大小
		write(rws, buf, 20);
		//再发图片内容
		write(rws, bufpic, len);
		printf("piclen = %d\n",len);
		len = 0;
		close(fd2);
		//sleep(1);
	}
}
